package com.moran.deepseek.service;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.moran.deepseek.domain.ChatCompletionResponse;
import com.moran.deepseek.domain.ChatCompletionParam;
import com.moran.deepseek.domain.ChatRequest;
import com.moran.deepseek.domain.ChatMessage;
import com.moran.deepseek.mapper.ChatMessageMapper;
import jakarta.annotation.Resource;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class ChatService {

    @Resource
    private OkHttpClient client;
    @Value("${bluefox.deepseek.base_url}")
    private String baseUrl;
    @Value("${bluefox.deepseek.api_key}")
    private String apiKey;

    @Resource
    private ChatMessageMapper chatMessageMapper;

    public String sendMessage(String userMessage) throws IOException {
        return sendChatCompletion(createDefaultRequest(userMessage));
    }

    private ChatRequest createDefaultRequest(String userMessage) {
        ChatRequest request = new ChatRequest();
        request.setMessages(List.of(
                new ChatRequest.Message("assistant", "You are a helpful assistant"),
                new ChatRequest.Message("user", userMessage)
        ));
        return request;
    }

    public String sendChatCompletion(ChatRequest request) throws IOException {
        String jsonBody = JSONUtil.toJsonStr(request);
        Request httpRequest = buildRequest(jsonBody);

        try (Response response = client.newCall(httpRequest).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException(buildErrorMessage(response));
            }
            // 解析响应体
            String responseBody = Objects.requireNonNull(response.body()).string();
            ChatCompletionResponse chatCompletionResponse = JSONUtil.toBean(responseBody, ChatCompletionResponse.class);

            // 提取第一个choice的消息内容
            if (chatCompletionResponse.getChoices() != null && !chatCompletionResponse.getChoices().isEmpty()) {
                return chatCompletionResponse.getChoices().get(0).getMessage().getContent();
            } else {
                throw new RuntimeException("No valid response from DeepSeek API.");
            }
        }
    }


    private Request buildRequest(String jsonBody) {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, jsonBody);

        return new Request.Builder()
                .url(baseUrl)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer " + apiKey)
                .build();
    }


    private String buildErrorMessage(Response response) throws IOException {
        return String.format("API请求失败: %d - %s",
                response.code(),
                response.body() != null ? response.body().string() : "无响应内容");
    }

    public String chatCompletion(String param) throws IOException {
        // 将传入的参数字符串转换为CompletionChatParam对象
        ChatCompletionParam bean = JSONUtil.toBean(param, ChatCompletionParam.class);
        String conversationId = bean.getConversation_id();
        String userMessage = bean.getMessage();

        // 查询数据库中的历史消息
        List<ChatMessage> historyChatMessages = chatMessageMapper.selectList(
                Wrappers.<ChatMessage>lambdaQuery()
                        .eq(ChatMessage::getConversationId, conversationId)
                        .orderByAsc(ChatMessage::getId) // 确保按时间顺序排列
        );

        // 构建请求消息列表
        List<ChatRequest.Message> messages = new ArrayList<>();
        for (ChatMessage msg : historyChatMessages) {
            messages.add(new ChatRequest.Message(msg.getUserRole(), msg.getUserContent()));
            messages.add(new ChatRequest.Message(msg.getAssistantRole(), msg.getAssistantContent()));
        }

        // 添加当前用户的提问
        messages.add(new ChatRequest.Message("user", userMessage));

        // 创建请求并发送
        ChatRequest request = new ChatRequest();
        request.setMessages(messages);

        // 发送聊天完成请求到DeepSeek API
        String responseMessage = sendChatCompletion(request);

        // 保存助手的回复到数据库
        ChatMessage assistantReply = new ChatMessage();
        assistantReply.setUserRole("user");
        assistantReply.setAssistantRole("assistant");
        assistantReply.setUserContent(userMessage); // 用户输入的内容
        assistantReply.setAssistantContent(responseMessage); // 助手的回复内容
        assistantReply.setConversationId(Integer.valueOf(conversationId));
        chatMessageMapper.insert(assistantReply);

        return responseMessage;
    }
}